let axios = require('axios');
let fs = require('fs');

var url = "https://www.wacai.com/activity/bkk-frontier/api/v2/flow/list/web?___t="+new Date();
var headerMap = {
    'Host': 'www.wacai.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    'Cache-Control': 'no-cache',
    'X-Platform': '0',
    'X-Mc': '0',
    'X-Appver': '',
    'X-Deviceid': '0',
    'Content-Length': '96',
    'Origin': 'https://www.wacai.com',
    'DNT': '1',
    'Connection': 'keep-alive',
    'Referer': 'https://www.wacai.com/activity/bkk-web/detail',
    'Cookie': 'sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2217689a50f7c17e5-0ea690be2cf26a8-4b5b66-1789670-17689a50fe047cbb%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2217689a50f7c17e5-0ea690be2cf26a8-4b5b66-1789670-17689a50fe047cbb%22%7D; wctk=WCeO2k48pytNz75PYLKsjMAOI0OceT4xrH_ug; wctk.sig=Ti4EdL9AmOTMCTIwm9Wrr96JctM; access_token=WCeO2k48pytNz75PYLKsjMAOI0OceT4xrH_ug; access_token.sig=tcYo8R_4yPM2zCC0p_RHqrIwygg; JSESSIONID=BDFCB7DE708A4496E708DDA9279CDC7F',
    'Sec-GPC': '1'
}

getData().then(datas=>{
    var flowList = datas.flatMap((data)=>{
        var flowList = data.flowList.map((flow)=>{

            var time = new Date(flow.bizTime)
            return {
                bizTime:time.getFullYear()+'/'+(time.getMonth()+1)+'/'+time.getDate(),
                categoryName:flow.categoryName,
                amount:(flow.amount/100).toFixed(2),
                comment:flow.comment
            }
        });

        return flowList;
    });
    let str = flowList.map((item)=>{
        return [item.bizTime,item.categoryName,item.amount,item.comment].join(',');
    }).join('\n');
    fs.writeFileSync('wacai.csv',str)

});

async function getData(){
    var data=[],collecData = [],pageIndex=1;
    do {
        var params = {
            "bkId": 103535881,
            "startTime": 1606780800000,
            "endTime": 1609459199999,
            "pageSize": 50,
            "pageIndex": pageIndex
        }
        let response = await axios.post(url,params,{
            headers: headerMap
        });
        data = response.data.data.dailyItems;
        if (data){
            collecData = collecData.concat(data);
            pageIndex+=1;
        }

    } while (data.length!=0)

    return collecData;
}
